<!--  -->
<template>
  <div class="landpage">
    <div class="land-swiper">
      <Swiper
        v-if="bannerItems.length > 0"
        :loop="true"
        :slides-per-view="'auto'"
        :autoplay="{ delay: 3000, pauseOnMouseEnter: true }"
        :pagination="{ clickable: true }"
        class="my-swiper"
      >
        <SwiperSlide v-for="(item, index) in bannerItems" :key="index">
          <div
            class="swiper-banner"
            :style="{ backgroundImage: `url(${item})` }"
          ></div>
        </SwiperSlide>
      </Swiper>
    </div>
    <div class="land-main">
      <div class="land-title">{{ info.title }}</div>
      <!-- <tabs :tabList="tabList" @tabChange="tabChange"></tabs> -->
      <div
        class="wrapper"
        ref="timeLineWrapperRef"
        style="margin-bottom: 0.3rem"
      >
        <div class="content">
          <div class="land-timeline">
            <timeline
              :direction="direction"
              :reverse="reverse"
              :timelineItems="timelineItems"
              :timestamp="timestamp"
              :type="type"
              :color="color"
              :size="size"
              :icon="icon"
              :dot="dot"
            ></timeline>
          </div>
        </div>
      </div>
      <div class="wrapper-box">
        <div class="wrapper" ref="wrapperRef">
          <div class="content">
            <div
              class="item"
              v-for="(item, index) in tabList"
              :key="index"
              :class="activeIdx == index ? 'on' : ''"
              @click="tabChange(index)"
            >
              {{ item.introduceName }}
            </div>
          </div>
        </div>
        <div class="line-tabs" v-if="tabList.length > 0"></div>
      </div>

      <div class="land-content" v-if="tabList.length > 0">
        <div class="land-ct-tl">{{ tabList[activeIdx].introduceName }}</div>
        <div
          class="land-ct-main"
          v-html="tabList[activeIdx].introduceDetail"
        ></div>
        <template v-for="(data, idx) in tabList[activeIdx].uploadIntroduceList">
          <div class="video-item">
            <video
              :src="data"
              muted
              controls
              :ref="(el) => setVideoRef(el, idx)"
              @play="handlePlay(idx)"
            ></video>
          </div>
        </template>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, toRefs, nextTick } from "vue";
import { Swiper, SwiperSlide } from "swiper/vue";
import SwiperCore from "swiper";
import { Autoplay, Pagination } from "swiper/modules";
import timeline from "./components/timeline.vue";
import { useRouter, useRoute } from "vue-router";
const route = useRoute();
const direction = ref("horizontal");
const timelineItems = ref([]);

import "swiper/css";
import "swiper/css/autoplay";
import "swiper/css/pagination";
SwiperCore.use([Autoplay, Pagination]);
import { showToast } from "vant";
import "vant/es/toast/style";

import BScroll from "better-scroll";
import Api from "@/api/index";

const bannerItems = ref([]);
const swiperRef = ref(null);

const matchId = ref("");
const info = ref({});
const tabList = ref([]);
const wrapperRef = ref(null);
let scroll = null;

const timeLineWrapperRef = ref(null);
let timeLinescroll = null;

const activeIdx = ref(0);
const init = () => {
  const id = route.query.matchId;
  // const id = "98471115701101826";
  matchId.value = id;
  Api.getInfoMs(id)
    .then(async (res) => {
      if (res.flag === 0) {
        const data = res.data;
        bannerItems.value = JSON.parse(data.banner);
        info.value = data;

        const eventTimeline = JSON.parse(data.eventTimeline);
        const list = formatTimeLineList(eventTimeline);
        for (var i = 0; i < list.length; i++) {
          const obj = {
            timestamp: list[i].label,
            content: eventTimeline[i].title,
            type: list[i].isOver
              ? "primary"
              : list[i].isActive
              ? "primary"
              : "info",
            isArrive: list[i].isOver,
          };
          timelineItems.value.push(obj);
        }
        tabList.value = data.configurationIntroduction
          ? JSON.parse(data.configurationIntroduction)
          : [];
        await nextTick();
        // 等待 DOM 更新后初始化或刷新 better-scroll
        if (tabList.value.length > 0) {
          if (!scroll && tabList.value.length > 0) {
            scroll = new BScroll(wrapperRef.value, {
              scrollX: true,
              scrollY: false,
              click: true,
            });
          } else {
            if (scroll) {
              scroll.refresh();
            }
          }
        }
        if (timelineItems.value.length > 0) {
          if (!timeLinescroll && timeLineWrapperRef.value) {
            timeLinescroll = new BScroll(timeLineWrapperRef.value, {
              scrollX: true,
              scrollY: false,
              click: false,
            });
          } else {
            if (timeLinescroll) {
              timeLinescroll.refresh();
            }
          }
        }
      } else {
        return showToast(res.msg);
      }
    })
    .catch((err) => {
      console.error(err);
      return showToast(err.response.data.message);
    });
};
// 存储所有 video 元素的 DOM 引用
const videoRefs = ref([]);
const setVideoRef = (el, index) => {
  if (el) {
    videoRefs.value[index] = el;
  }
};

const handlePlay = (currentIndex) => {
  videoRefs.value.forEach((video, index) => {
    if (video && index !== currentIndex && !video.paused) {
      video.pause();
    }
  });
};

const tabChange = (data) => {
  activeIdx.value = data;
};

const formatDate = (dateStr) => {
  if (!dateStr) return "";
  const d = new Date(dateStr);
  const mm = String(d.getMonth() + 1).padStart(2, "0");
  const dd = String(d.getDate()).padStart(2, "0");
  return `${mm}.${dd}`;
};

const formatTimeLineList = (list) => {
  const now = Date.now();

  return list
    .map((item, index, arr) => {
      const startStr = formatDate(item.startTime);
      const endStr = item.endTime ? formatDate(item.endTime) : "";

      const startTime = item.startTime
        ? new Date(item.startTime).getTime()
        : null;

      // 自动补全天结束时间
      let endTime = null;
      if (item.endTime) {
        const endDate = new Date(item.endTime);
        endDate.setHours(23, 59, 59, 999);
        endTime = endDate.getTime();
      } else if (item.startTime) {
        const endDate = new Date(item.startTime);
        endDate.setHours(23, 59, 59, 999);
        endTime = endDate.getTime();
      }

      let label = "";
      if (startStr && endStr) {
        label = `${startStr} - ${endStr}`;
      } else if (startStr) {
        label = startStr;
      } else {
        return null;
      }

      let isOver = false;
      let isActive = false;

      if (startTime !== null && endTime !== null) {
        if (now >= startTime && now <= endTime) {
          isActive = true;
        } else if (now > endTime) {
          isOver = true;
        }
      }

      return {
        label,
        isOver,
        isActive,
      };
    })
    .filter((item) => item !== null);
};

onMounted(async () => {
  init();
});
</script>

<style lang='scss' scoped>
@import "../../assets/scss/landingpage.scss";
</style>
<style  lang='scss'>
.land-ct-main {
  p {
    font-size: 0.3rem;
    line-height: 0.42rem;
  }
  li {
    font-size: 0.3rem;
  }
  img {
    max-width: 100%;
  }
}

table {
  width: 100% !important;
  max-width: 100%;
  border-collapse: collapse; /* 合并边框 */
  table-layout: auto;
  word-break: break-word;
  margin-bottom: 0.32rem;
}

th,
td {
  border: 1px solid #ccc; /* 边框颜色可自定义 */
  padding: 8px 12px; /* 内边距，增强可读性 */
  text-align: left; /* 根据需要调整 */
}

th {
  background-color: #f5f5f5; /* 灰色背景 */
  font-weight: bold;
}
.swiper-pagination-bullet {
  background-color: #cccccc !important;
  opacity: 1 !important;
}
.swiper-pagination-bullet-active {
  background-color: #ff9c22 !important;
}
</style>